import { loginout } from '@/services/login';
import {BookOutlined, LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons';
import {Avatar, Menu, message, Spin} from 'antd';
import type { ItemType } from 'antd/lib/menu/hooks/useItems';
import { stringify } from 'querystring';
import type { MenuInfo } from 'rc-menu/lib/interface';
import React, { useCallback, useEffect } from 'react';
import { history, useModel } from 'umi';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import { flushSync } from 'react-dom';
import {FILE_URL} from "../../../proxyConfig";

export type GlobalHeaderRightProps = {
  menu?: boolean;
};

/**
 * 退出登录，并且将当前的 url 保存
 */
const loginOut = async () => {

  await loginout({});
  sessionStorage.clear();
  const { search, pathname } = window.location;
  const urlParams = new URL(window.location.href).searchParams;
  /** 此方法会跳转到 redirect 参数所在的位置 */
  const redirect = urlParams.get('redirect');
  // Note: There may be security issues, please note
  if (window.location.pathname !== '/user/login' && !redirect) {
    history.replace({
      pathname: '/user/login',
      search: stringify({
        redirect: pathname + search,
      }),
    });
  }
};

const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu }) => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const  downloadFile = (url, fileName) =>{
    const hide = message.loading('正在下载文件，请稍等！');
    const x = new XMLHttpRequest()
    x.open("GET", url, true)
    x.responseType = 'blob'
    x.onload = function (e) {
      const url = window.URL.createObjectURL(x.response)
      const a = document.createElement('a')
      a.href = url
      a.target = '_blank'
      a.download = fileName
      a.click()
      hide()
      a.remove()
    }
    x.send()
  }

  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const { key } = event;
      if(key=='yhsc'){
        const fileUrl = FILE_URL+'upload/help/'+currentUser?.authId+'.doc'
        // window.open(fileUrl)
        downloadFile(fileUrl,'用户手册.doc')
        return
      }
      if (key === 'logout' && initialState) {
        flushSync(() => {
          setInitialState((s) => ({ ...s, currentUser: undefined }));
        });
        loginOut();
        return;
      }
      history.push(`/account/${key}`);
    },
    [initialState, setInitialState],
  );


  const loading = (
    <span className={`${styles.action} ${styles.account}`}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }



  if (!currentUser || !currentUser.name) {
    return loading;
  }
  const menuItems: ItemType[] = [
    {
      key: 'updateData',
      icon: <UserOutlined />,
      label: '修改资料',
    },
    {
      type: 'divider' as const,
    },
    {
      key: 'yhsc',
      icon: <BookOutlined />,
      label: '用户手册',
    },
    {
      type: 'divider' as const,
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    },
  ];

  return (
    <HeaderDropdown
      menu={{
        selectedKeys: [],
        onClick: onMenuClick,
        items: menuItems,
      }}
    >
      <span className={`${styles.action} ${styles.account}`}>
        <Avatar size="small" className={styles.avatar} src={currentUser.avatar} alt="avatar" />
        <span className={`${styles.name} anticon`}>{currentUser.name}</span>
      </span>
    </HeaderDropdown>
  );
};

export default AvatarDropdown;
